import React, { createContext, useContext, useState } from "react";
import type { IProfile } from "../api/login/type";

// 定义上下文类型，包含用户信息和更新用户信息的方法
type UserInfoContextType = {
  userInfo: IProfile | null;
  setUserInfo: (userInfo: IProfile | null) => void;
};

// 创建上下文
const UserInfoContext = createContext<UserInfoContextType | undefined>(
  undefined,
);

// 提供器组件
export function UserInfoProvider({ children }: { children: React.ReactNode }) {
  const [userInfo, setUserInfo] = useState<IProfile | null>(null);

  return (
    <UserInfoContext.Provider value={{ userInfo, setUserInfo }}>
      {children}
    </UserInfoContext.Provider>
  );
}

// 自定义 Hook 用于获取用户信息和更新方法
export function useUserInfo() {
  const context = useContext(UserInfoContext);
  if (context === undefined) {
    throw new Error("useUserInfo must be used within a UserInfoProvider");
  }
  return context;
}
